package com.qf.fengmimall.user.controller;

import cn.hutool.jwt.JWT;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qf.fengmimall.constant.Constants;
import com.qf.fengmimall.ex.UserException;
import com.qf.fengmimall.user.entity.Users;
import com.qf.fengmimall.user.service.IUsersService;
import com.qf.fengmimall.vo.ResultVo;
import com.qf.fengmimall.vo.UserVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;
import java.util.Date;

/**
 * <p>
 * 用户  前端控制器
 * </p>
 *
 * @author lx
 * @since 2023-02-13
 */
@RestController
@RequestMapping("/user")
@CrossOrigin
@Slf4j
public class UsersController {

    @Autowired
    private IUsersService usersService;

    /**
     * 用户登入
     *
     * @param username 用户名
     * @param password 密码
     * @return
     */
    @RequestMapping("/login")
    public ResultVo login(String username, String password) throws UserException, JsonProcessingException {
        log.debug("接收到的参数为username={0},password=={0}", username, password);
        if (username.equals("")) {
            throw new UserException("用户名不能为空");
        }
        if (password.equals("")) {
            throw new UserException("密码不能为空");
        }
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);
        subject.login(usernamePasswordToken);
        PrincipalCollection principals = subject.getPrincipals();
        Users users = (Users) principals.getPrimaryPrincipal();
        //创建json装换器对象 由jackson类库提供
        ObjectMapper objectMapper = new ObjectMapper();
        //user ==》json字符串
        String userJson = objectMapper.writeValueAsString(users);
        //创建JWT对象，将通过验证的用户信息以json字符串放入有效载荷中(PAYLOAD),设置token有效时间，设置秘钥或盐，生成token字符串
        String token = JWT.create().setPayload("sub", userJson).setExpiresAt(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 14))
                .setIssuer("fengmimall").setKey(Constants.SECRET.getBytes(StandardCharsets.UTF_8)).sign();

        //token信息返回给浏览器端
        ResultVo ok = ResultVo.ok(users);
        ok.put("msg", token);

        return ok;
    }

    /**
     * 注册
     *
     * @param userVo
     * @return
     * @throws UserException
     */
    @RequestMapping("/regist")
    public ResultVo registe(@RequestBody UserVo userVo) throws UserException {
        log.debug("接收到的参数userVo={0}", userVo);
        usersService.registe(userVo);
        return ResultVo.ok();
    }

}
